package com.my.oschina.fragment;

import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockListFragment;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.my.oschina.R;
import com.my.oschina.adapter.ListViewActiveAdapter;
import com.my.oschina.app.AppContext;
import com.my.oschina.app.AppException;
import com.my.oschina.bean.Active;
import com.my.oschina.bean.UserInformation;

/**
 * 动态
 * 
 * @author XuShaoJie
 * @version 2013-07-13
 */
public class ActiveFragment extends SherlockListFragment {

	private int mInstance = -1;

	private PullToRefreshListView mPullRefreshListView;
	private ListViewActiveAdapter mNewsAdapter;
	private List<Active> lvNewsDataList = new ArrayList<Active>();
	private int lvSumData;// 加载的总数目

	private AppContext appContext;// 全局Context

	/**
	 * 返回查看用户信息的时候，加载的博客列表
	 * 
	 * @param hisUid
	 * @param hisName
	 * @return
	 */
	public static ActiveFragment newInstance(int uid, int hisUid, String hisName) {
		ActiveFragment ff = new ActiveFragment();
		Bundle bundle = new Bundle();
		bundle.putInt("uid", uid);
		bundle.putInt("hisUid", hisUid);
		bundle.putString("hisName", hisName);
		ff.setArguments(bundle);

		return ff;
	}

	private int getArgsUid() {
		return getArguments().getInt("uid", 0);
	}

	private int getArgsUserId() {
		return getArguments().getInt("hisUid");
	}

	private String getArgsUserName() {
		return getArguments().getString("hisName");
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		appContext = (AppContext) getSherlockActivity().getApplication();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
//		if (savedInstanceState != null) {
//			mInstance = savedInstanceState.getInt("mInstance");
//		}
		View view = inflater.inflate(R.layout.activity_ptr_list, container,
				false);
		mPullRefreshListView = (PullToRefreshListView) view
				.findViewById(R.id.pull_refresh_list);
		mPullRefreshListView.setMode(Mode.BOTH);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		// Set a listener to be invoked when the list should be refreshed.
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						String label = DateUtils.formatDateTime(appContext,
								System.currentTimeMillis(),
								DateUtils.FORMAT_SHOW_TIME
										| DateUtils.FORMAT_SHOW_DATE
										| DateUtils.FORMAT_ABBREV_ALL);

						// Update the LastUpdatedLabel
						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel(label);

						if (mPullRefreshListView.getCurrentMode() == Mode.PULL_FROM_START) {
							lvNewsDataList.clear();
							lvSumData = 0;
							mNewsAdapter.notifyDataSetChanged();
						}

						// 加载数据异步处理任务
						new GetFansTask().execute();
					}
				});

		mNewsAdapter = new ListViewActiveAdapter(getSherlockActivity(),
				lvNewsDataList, R.layout.active_listitem, false);
		mPullRefreshListView.setAdapter(mNewsAdapter);

		// TODO 第一次启动时候加载数据
		new GetFansTask().execute();

	}

	/**
	 * 加载数据AsyncTask
	 */
	private class GetFansTask extends AsyncTask<String, Void, UserInformation> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
					true);
		}

		@Override
		protected UserInformation doInBackground(String... params) {
			// 当前pageIndex
			int pageIndex = lvSumData / 20;
			try {
				return appContext.getInformation(getArgsUid(), getArgsUserId(),
						getArgsUserName(), pageIndex, true);
			} catch (AppException e) {
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(UserInformation result) {
			super.onPostExecute(result);
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
					false);
			mPullRefreshListView.onRefreshComplete();

			// 加载成功且如果有数据
			if (result != null && result.getActivelist().size() > 0) {
				
				List<Active> friendList = result.getActivelist();
				lvSumData += friendList.size();
				lvNewsDataList.addAll(friendList);
				mNewsAdapter.notifyDataSetChanged();

				if (friendList.size() < 20) {
					mPullRefreshListView.setMode(Mode.PULL_FROM_START);
					// 添加监听器
					mPullRefreshListView
							.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
								@Override
								public void onLastItemVisible() {
									Toast.makeText(getSherlockActivity(),
											"已加载全部", Toast.LENGTH_SHORT).show();
								}
							});

				} else if (friendList.size() == 20) {
					mPullRefreshListView.setMode(Mode.BOTH);
					// 取消监听
					mPullRefreshListView.setOnLastItemVisibleListener(null);
				}
			}
			// 加载失败或者没有数据
			else {
				Toast.makeText(getSherlockActivity(), "加载失败或者没有动态",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
//		outState.putInt("mInstance", mInstance);
	}

}
